package com.easylinkin.linkappapi.openapi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.easylinkin.linkappapi.openapi.dto.AapplicationCopyModelDTO;
import com.easylinkin.linkappapi.openapi.service.ApplicationCopyService;
import com.easylinkin.linkappapi.openapi.service.ApplicationCopyhandleUnifiedService;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.security.service.LinkappUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: linkapp-group-cloud
 * @description: 应用拷贝
 * @author: chenkaixuan
 * @create: 2021-09-08 17:18
 */
@Service
@Slf4j
public class ApplicationCopyServiceImpl implements ApplicationCopyService {
    @Resource
    List<ApplicationCopyhandleUnifiedService> applicationCopyhandleUnifiedServiceList;
    @Resource
    private LinkappUserService userService;

    @Override
    @Async
    public RestMessage copy(AapplicationCopyModelDTO applicationCopyModel) {
        log.info("应用拷贝applicationCopy被调用参数是:{}", JSONObject.toJSONString(applicationCopyModel));
        Assert.notNull(applicationCopyModel, "参数不能为空");
        Assert.notNull(applicationCopyModel.getOldUserName(), "oldUserName 不能为空");
        Assert.notNull(applicationCopyModel.getNewUserName(), "newUserName 不能为空");

        LinkappUser oldLinkappUser = userService.findByUsername(applicationCopyModel.getOldUserName());
        Assert.notNull(oldLinkappUser, applicationCopyModel.getOldUserName() + "用户不存在");
        LinkappUser newLinkappUser = userService.findByUsername(applicationCopyModel.getNewUserName());
        Assert.notNull(newLinkappUser, applicationCopyModel.getNewUserName() + "用户不存在");
        //执行拷贝
        for (ApplicationCopyhandleUnifiedService copyService : applicationCopyhandleUnifiedServiceList) {
            RestMessage restMessage = copyService.copy(newLinkappUser, oldLinkappUser);
            if (restMessage != null && !restMessage.isSuccess()) {
                throw new IllegalArgumentException(copyService.getClass() + ":" + restMessage.getMessage());
            }
            restMessage = copyService.copy(applicationCopyModel.getScreenMapperMap(), applicationCopyModel.getDeviceMapperMap(), newLinkappUser, oldLinkappUser);
            if (restMessage != null && !restMessage.isSuccess()) {
                throw new IllegalArgumentException(copyService.getClass() + ":" + restMessage.getMessage());
            }
        }
        return RestBuilders.successBuilder().build();
    }
}
